
from server.common.CommonHandler import CommonHandler
from trest.router import post
import json
import pandas as pd
from pandas.io.json import json_normalize
import server.common.Global_Var_Model as gl
import server.Search_Work as Search_Work
import server.Trade_Work as TradeWork
import uuid
import time
from  configs import API_Config
import datetime


def InputQueue(_json):
    """ 输入一个dataframe 加入队列中 """
    data_list = json.loads(_json)  # 字符串转json
    if isinstance(data_list,str):
        data_list = json.loads(data_list)

    for item in data_list:
        item["entrust_no"] = str(item["entrust_no"])
        item["stock_no"] = str(item["code"]).split('.')[0]
        item["stock_name"] = str(item["name"])
        item["volume"] = str(item["volume"])
        item["price"] = str(item["price"])
        item["key"] = str(uuid.uuid1())
        item["status"] = 0

    df_1 = json_normalize(data_list)  # json转换dataframe
    df_1.head()
    df = df_1.loc[:, API_Config.cfg['activework_field']]  # 获取csv 指定列
    # 接收到新的指令时加入到dataframe中 并存储一份
    gl.gl_queue_DF_Data = pd.concat([gl.gl_queue_DF_Data, df])  # 连接两个dataframe
    gl.gl_queue_DF_Data = gl.gl_queue_DF_Data.loc[:, API_Config.cfg['activework_field']]  # 连接后指定列
    gl.gl_queue_DF_Data = gl.gl_queue_DF_Data.reset_index(drop=True)  # 重建索引
    gl.gl_queue_DF_Data = gl.gl_queue_DF_Data.loc[:, API_Config.cfg['activework_field']]  # 取值列保存到csv
    gl.gl_queue_DF_Data.to_csv(API_Config.cfg['activework_path'], sep='\t')

def SearchData(_json):

    """ 查询结果 """
    current_time = datetime.datetime.now()
    print("开始查询时间为:", current_time)
    # 接收到新的指令时加入到dataframe中 并存储一份
    item = json.loads(_json)  # 字符串转json
    # 传入的策略号返回数据集
    df = Search_Work.searchWork(item)
    resJSON = df #.to_dict('records')
    current_time = datetime.datetime.now()
    print("结束查询时间为:", current_time)
    return resJSON

def TradeData(_json):
     
    """ 交易结果 """
    current_time = datetime.datetime.now()
    print("开始交易时间为:", current_time)
    # 接收到新的指令时加入到dataframe中 并存储一份
    item = json.loads(_json)  # 字符串转json
    # 传入的策略号返回数据集
    df = TradeWork.tradeWork(item)
    resJSON = df #.to_dict('records')
    current_time = datetime.datetime.now()
    print("结束交易时间为:", current_time)
    return resJSON